<template>
  <el-dialog title="银台结账" :close-on-click-modal="false" :visible.sync="visible" fullscreen center>
		<el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-divider content-position="left">顾客信息</el-divider>
    <el-form>
      <el-row style="background-color: #ecf5ff;padding: 5px 10px;">
        <el-col :span="5">
          <el-form-item label="顾客姓名">
            {{customerData.customerName}}
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="顾客卡号">
            {{customerData.customerCard}}
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-button icon="el-icon-collection" type="primary" style="margin-top: 3px;">详情</el-button>
        </el-col>
      </el-row>

    </el-form>
    <div>
      <el-divider content-position="left">查询信息</el-divider>
      <el-table class="miui-table" :data="dataList" border style="margin-bottom: 15px;">
        <el-table-column prop="billId" label="销售单号"></el-table-column>
        <el-table-column prop="createUserName" label="销售人员"></el-table-column>
        <el-table-column prop="originalPrice" label="原价合计"></el-table-column>
        <el-table-column prop="discountPrice" label="折扣金额"></el-table-column>
        <el-table-column prop="removePrice" label="抹零金额"></el-table-column>
        <el-table-column prop="receivablePrice" label="应收金额"></el-table-column>
        <el-table-column prop="paidPrice" label="实缴金额"></el-table-column>
        <el-table-column prop="totalIntegral" label="获取积分"></el-table-column>
      </el-table>

      <el-table class="miui-table" :data="goodsList" border style="margin-bottom: 15px;">
        <el-table-column prop="goodsCode" label="商品代码" width="170"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称"></el-table-column>
        <el-table-column prop="price" label="单价" width="90"></el-table-column>
        <el-table-column prop="goodsQuantity" label="数量" width="60"></el-table-column>
        <el-table-column prop="originalPrice" label="原价合计" width="90"></el-table-column>
        <el-table-column prop="discountRate" label="折扣率" width="80"></el-table-column>
        <el-table-column prop="discountPrice" label="折扣金额" width="90"></el-table-column>
        <el-table-column prop="removePrice" label="抹零金额" width="90"></el-table-column>
        <el-table-column prop="receivablePrice" label="应收金额" width="90"></el-table-column>
        <el-table-column prop="integral" label="累计积分" width="80"></el-table-column>
      </el-table>
      <el-table class="miui-table" :data="feeList" border style="margin-bottom: 15px;">
        <el-table-column prop="feeName" label="附加费用"></el-table-column>
        <el-table-column prop="price" label="单价"></el-table-column>
        <el-table-column prop="quantity" label="数量"></el-table-column>
        <el-table-column prop="totalPrice" label="应收金额"></el-table-column>
        <!-- <el-table-column prop="integral" header-align="center" align="center" label="累计积分"></el-table-column> -->
      </el-table>

      <el-form label-width="80px" style="margin-bottom: 15px;">
        <el-row style="background-color: #ecf5ff;padding: 5px 10px;">
          <el-col :span="4">
            <el-form-item label="应缴金额">
              <el-input v-model="paidPrice" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="缴费金额">
              <el-input v-model="payValue" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div style="color: red;" class="red">
              <el-form-item label="找零金额">
                <el-input v-model="change" readonly></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="4">
            <div style="color: red;" class="red">
              <el-form-item label="欠款金额">
                <el-input v-model="arrears" readonly></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <payment-form :cardType="customerData.cardType" :saleType="saleType" :paidPrice="paidPrice" :paymentDataList="paymentDataList" @refreshFormData="getPaymentValue" :show="true" :show2="show2" :integralBalance="integralBalance" :integralBalanceSum="integralBalanceSum" :integralDeductionTotal="integralDeductionTotal" :advancePayment="advancePayment" :moneyBalance="moneyBalance"></payment-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="paymentHandle" :loading="ischeck" v-prevent-re-click>缴 费</el-button>
      <el-button @click="clearAllInput">清 空</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {mapGetters} from 'vuex'

  import PaymentForm from '@/components/business/Payment'

  import { getSaleDetail, paymentConduct } from '@/api/eims/cashier/payment'
  import {getCustomerInfoObj} from '@/api/eims/customer'
  import {getSumIntegralByCustomerId2, getInfoByCustomerId}from '@/api/eims/familygroup'

	import { getObj } from '@/api/admin/dept'
  import { getUnitObj } from '@/api/admin/unit'

  export default {
    props:['saleDataList'],
    data() {
      return {
				ischeck: false,
        visible: false,
        saleId: '',
        customerData: {
        },
        saleType: '',
        integralDeductionTotal: '',
        dataList: [],
        goodsList: [],
        feeList: [],
        paymentDataList: [
          {method: '1', name: '现金',button: false, cost: ''},
          {method: '2', name: '积分',button: true, cost: ''},
          {method: '3', name: '储值卡',button: true, cost: '',cardNum: ''},
          {method: '4', name: '银行卡',button: true, cost: '',vouchersNum: ''},
          {method: '5', name: '代金券',button: true, cost: ''},
          {method: '6', name: '预付款',button: true, cost: ''},
          {method: '8', name: '余额支付',button: true, cost: ''},
        ],
        paidPrice: '',
        payValue: '',
        payInfo: {},
        integralBalance: '',
        integralBalanceSum: '',
        advancePayment: '',
        moneyBalance: '',
        show2: false
      }
    },
    components:{
      PaymentForm
    },
    computed: {
      ...mapGetters(['permissions','userInfo']),
      change(){
        if(this.paymentDataList[0].cost < 0){
          let lll = (Math.abs(this.paymentDataList[0].cost)).toFixed(2)
          this.paymentDataList[0].cost = '0.00'
          return lll
        }else{
          if(Number(this.payValue - this.paidPrice) > 0){
            return (this.payValue - this.paidPrice).toFixed(2)
          }else{
            return '0.00'
          }
        }
      },
      arrears(){
        if(Number(this.payValue - this.paidPrice) < 0){
          return (Math.abs(this.payValue - this.paidPrice)).toFixed(2)
        }else{
          return '0.00'
        }
      }
    },
    methods:{
      // 打开弹窗，初始化数据
      init(data){
        this.visible = true
        this.saleId = data.id
        this.dataList = []
        this.paymentDataList = [
          {method: '1', name: '现金',button: false, cost: '',cashType: '1'},
          {method: '2', name: '积分',button: true, cost: ''},
          {method: '3', name: '储值卡',button: true, cost: '',cardNum: ''},
          {method: '4', name: '银行卡',button: true, cost: '',vouchersNum: ''},
          {method: '5', name: '代金券',button: true, cost: ''},
          {method: '6', name: '预付款',button: true, cost: ''},
          {method: '8', name: '余额支付',button: true, cost: ''},
        ],
        this.getDeptType()
        this.$nextTick(() => {
          this.paidPrice = data.receivablePrice.toFixed(2)
          this.payValue = data.receivablePrice.toFixed(2)
          this.paymentDataList[0].cost = data.receivablePrice.toFixed(2)
          this.dataList.push(data)
          this.getSaleGoodsDetail()
          getCustomerInfoObj(data.customerId).then(response => {
            if(response.data.code == '0'){
              this.advancePayment = response.data.data.advancePayment
              this.moneyBalance = response.data.data.moneyBalance
              if(this.userInfo.lessDeptId ==24||this.userInfo.lessDeptId == 26 ||this.userInfo.lessDeptId == 27||this.userInfo.lessDeptId == 28||this.userInfo.lessDeptId == 51){
                this.integralBalance = response.data.data.storesIntegral
              }else{
                this.integralBalance = response.data.data.integral
              }
              this.customerData.cardType = response.data.data.cardType
              this.customerData.customerName = response.data.data.name
              this.customerData.customerCard = response.data.data.customerCard
            }else{
              this.$message.error(response.data.msg)
            }

          })
          getSumIntegralByCustomerId2(data.customerId,this.userInfo.lessDeptId).then(response => {
            if(response.data.code == 0){
              if(response.data.data == 0){
                this.show2 = false
                this.integralBalanceSum = 0
              }else{
                this.show2 = true
                this.integralBalanceSum = response.data.data
              }
            }else{
              this.$message.error(response.data.msg)
            }
          })
        })
      },

			// 获取当前部门类型信息
			getDeptType(){
        let deptId = this.userInfo.lessDeptId
        getObj(deptId).then(response => {
          let unitId = response.data.data.unitId
          getUnitObj(unitId).then(result => {
            this.hospitalFlag = result.data.data.hospitalFlag
          })
        })
			},
      //  获取销售单销售商品信息
      getSaleGoodsDetail() {
        getSaleDetail({saleId:this.saleId}).then(response => {
          if(response.data.code == '0'){
            this.saleType = response.data.data.saleType
            this.integralDeductionTotal = response.data.data.integralDeductionTotal
            this.goodsList = response.data.data.detailList
            this.feeList = response.data.data.feeList
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //  获取缴费数据
      getPaymentValue(data) {
        this.payValue = data
      },

      //  表单提交，缴费
      paymentHandle() {
        let list = []
				let cashTypeList = []
        this.paymentDataList.forEach(item => {
          if(item.cashType){
            cashTypeList.push(item.cashType)
          }
          if(item.cost){
            if(item.method == '3'){
              list.push({method:item.method,cardNum: item.cardNum,totalPrice: item.cost})
            }else if(item.method == '1'){
              list.push({method:item.method,cashType: item.cashType,totalPrice: item.cost})
            }else{
              list.push({method:item.method,totalPrice: item.cost})
            }
          }
        })
        if(this.checkArrayElement(cashTypeList) > 0){
          this.$message.warning('同一种付款方式只能使用一次')
          return false
        }

				let result1 = true

        list.some(item => {
          result1 = true
          if(item.totalPrice < 0) {
            return result1 = false
          }
        })
        if(result1){
          this.ischeck = true
          this.payInfo = list
          let payInfoDTO = { id: this.saleId,arrears: this.arrears, payInfo: this.payInfo }
          if(this.hospitalFlag == 1){
            if(this.payValue == this.paidPrice && this.change == '0.00') {
              paymentConduct(payInfoDTO).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('结款成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            }else{
              this.$message.warning('请核对缴费金额')
              this.ischeck = false
            }
          }else{
            if(this.payValue == this.paidPrice || this.paidPrice == ((parseFloat(this.payValue)*100  + parseFloat(this.arrears)*100)/100)) {
              paymentConduct(payInfoDTO).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('结款成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            }else{
              this.$message.warning('请核对缴费金额')
              this.ischeck = false
            }
          }

        }else{
          this.$message.warning('请检查缴费金额')
          this.ischeck = false
        }
      },
      clearAllInput() {
        this.paymentDataList.forEach(item => {
          item.cost = ''
        })
      },
      checkArrayElement(array){
        array.sort();  //数组排序
        var reNum = 0;  //返回结果
        //遍历整个数组对象
        for(var i=0;i<array.length;i++){
             //跳过最后一个元素的比较
            if (i + 1 == array.length) {
                continue;
            }
            //判断相邻的元素是否相同
            if (array[i] == array[i + 1]) {
                reNum += 1;
            }
        }
        return reNum;
      }

    }
  }
</script>

<style>
  .red .el-form-item__label {
    color: red;
  }
  .red .el-input__inner {
    color: red;
  }
</style>
